package org.JWCB.common.security.valid.validator;


import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.JWCB.common.security.valid.innotation.AllowedValues;

public class AllowedValuesValidator implements ConstraintValidator<AllowedValues, Object> {

    private String[] allowedValues;
    private boolean canNull;
    @Override
    public void initialize(AllowedValues constraintAnnotation) {
        this.allowedValues = constraintAnnotation.value();
        this.canNull = constraintAnnotation.canNull();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return canNull; // 根据需要调整null处理
        }

        Class<?> valueType = value.getClass();
        for (String allowedStr : allowedValues) {
            try {
                Object convertedValue = convert(allowedStr, valueType);
                if (value.equals(convertedValue)) {
                    return true;
                }
            } catch (Exception e) {
                // 转换失败，跳过该值
            }
        }

        return false;
    }

    // 将字符串转换为目标类型
    private Object convert(String valueStr, Class<?> targetType) {
        if (targetType == String.class) {
            return valueStr;
        } else if (targetType == Integer.class || targetType == int.class) {
            return Integer.parseInt(valueStr);
        } else if (targetType == Long.class || targetType == long.class) {
            return Long.parseLong(valueStr);
        } else if (targetType == Double.class || targetType == double.class) {
            return Double.parseDouble(valueStr);
        } else if (targetType == Float.class || targetType == float.class) {
            return Float.parseFloat(valueStr);
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return Boolean.parseBoolean(valueStr);
        } else if (targetType.isEnum()) {
            return Enum.valueOf((Class<Enum>) targetType, valueStr);
        } else {
            throw new IllegalArgumentException("不支持的类型: " + targetType);
        }
    }
}